<template>
  <div class="folder-selector">
    <el-dropdown trigger="click" @command="handleCommand">
      <el-button type="primary">
        {{ selectedFolder || '选择文件夹' }}
        <el-icon class="el-icon--right"><arrow-down /></el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-tree
            ref="treeRef"
            :data="processedTreeData"
            :props="defaultProps"
            node-key="path"
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            :current-node-key="externalSelectedFolder?.path"
            class="folder-tree"
          />
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'

const props = defineProps({
  treeData: {
    type: Array,
    required: true
  },
  selectedFolder: {
    type: Object,
    default: null
  },
  directories: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['folder-selected'])

const treeRef = ref(null)
const selectedFolder = ref('')
const externalSelectedFolder = ref(props.selectedFolder)

// 监听外部传入的 selectedFolder 变化
watch(() => props.selectedFolder, (newVal) => {
  externalSelectedFolder.value = newVal
})

// 根据 directories 参数处理树数据
const processedTreeData = computed(() => {
  if (!props.directories) {
    return props.treeData
  }
  
  // 递归过滤树数据，只保留目录项
  const filterDirectories = (nodes) => {
    if (!Array.isArray(nodes)) return []
    
    return nodes
      .filter(node => node.directory)
      .map(node => ({
        ...node,
        children: node.children ? filterDirectories(node.children) : []
      }))
  }
  
  return filterDirectories(props.treeData)
})

const displayText = computed(() => {
  return externalSelectedFolder.value?.name || selectedFolder.value
})

const defaultProps = {
  children: 'children',
  label: 'name',
  disabled: (data) => !data.directory
}

const handleNodeClick = (data) => {
  if (data.directory) {
    selectedFolder.value = data.path
    emit('folder-selected', data)
    // 关闭下拉菜单
    document.querySelector('.el-dropdown-menu').click()
  }
}

const handleCommand = (command) => {
  // 可以在这里处理其他命令
}
</script>

<style scoped>
.folder-selector {
  display: inline-block;
  margin-right: 10px;
}

.folder-tree {
  min-width: 120px;
  padding: 5px;
  max-height: 300px;
  overflow-y: auto;
}

.el-tree-node__content {
  height: 36px;
}

:deep(.el-dropdown-menu) {
  padding: 0;
}
</style>